package org.luxor.commons.core.utils;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 实体对象转换器
 *
 * @author admin @date 2019/9/15 15:37 @version 0.0.1
 */
public class BeanUtils {

    /**
     * 实体对象转换器
     *
     * @param toClass 目标类型
     * @param from    来源对象
     * @return 目标对象
     */
    public static <T> T transform(Class<T> toClass, Object from) {
        if (from == null) {
            return null;
        }
        T toInstance = null;
        try {
            toInstance = toClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        org.springframework.beans.BeanUtils.copyProperties(from, toInstance, getNullPropertyNames(from));
        return toInstance;
    }

    /**
     * 实体对象转换器
     *
     * @param toClass 目标类型
     * @param from    来源Map
     * @return 目标对象
     */
    public static <T> T toObject(Class<T> toClass, Map from) {
        try {
            T obj = toClass.newInstance();
            if (from == null) {
                return obj;
            }
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                if (from.containsKey(field.getName())) {
                    field.set(obj, from.get(field.getName()));
                }
            }
            return obj;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String[] getNullPropertyNames(Object from) {
        final BeanWrapper src = new BeanWrapperImpl(from);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<String>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
